import json
import random
import re

from django.contrib.auth import login
from django.http import HttpResponse, JsonResponse
from django.middleware.csrf import get_token
from django.views import View
from django_redis import get_redis_connection
from meiduo_mall.libs.captcha.captcha import captcha
import logging

from meiduo_mall.libs.yuntongxun.ccp_sms import CCP

from users.models import User

logger = logging.getLogger('django')


class ImageCodeView(View):
    def get(self, request, uuid):
        '''图片验证码发送
        ① 请求图片验证码(传递uuid)
        ② 在视图里接收请求,生成图形验证码
        ③ 保存图片验证码在redis数据库
        ④ 响应并返回图形验证码
        '''
        text, image = captcha.generate_captcha()

        redis_conn = get_redis_connection('verify_code')
        redis_conn.set('img_%s' % uuid, text, 300)

        return HttpResponse(image, content_type='image/jpg')


class SMSCodeView(View):
    def get(self, request, mobile):
        """ 短信验证码发送
        ① 请求短信验证码(传递参数mobile)
        ② 接收,校验参数(在页面获取的图片验证码的真实数据和uuid)
        ③ 提取图形验证码, 对比图形验证码(加载页面时在redis里存入的图片验证码的text和uuid)
        ④ 生成短信验证码,保存(短信验证码[随机数])
        ⑤ 响应并给用户返回短信验证码
        """
        redis_conn = get_redis_connection('verify_code')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return JsonResponse({
                'code': 400,
                'message': '短信发送过于频繁'
            })

        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        if not all([image_code, uuid]):
            return JsonResponse({
                'code': 400,
                'message': '缺少必传参数'
            })
        # 通过uuid找到加载页面时在redis里存入的图片验证码的text
        redis_conn = get_redis_connection('verify_code')
        image_code_redis = redis_conn.get('img_%s' % uuid)

        if image_code_redis is None:
            return JsonResponse({
                'code': 400,
                'message': '图片验证码失效'
            })

        if image_code != image_code_redis:
            return JsonResponse({
                'code': 400,
                'message': '图片验证码输入错误'
            })

        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)

        sms_code = '%06d' % random.randint(0, 999999)
        logger.info('短信验证码为: %s' % sms_code)

        redis_conn.set('sms_%s' % mobile, sms_code, 300)

        redis_conn.set('send_flag_%s' % mobile, 1, 60)

        # CCP().send_template_sms(mobile, [sms_code, 5], 1)

        return JsonResponse({
            'code': 0,
            'message': '短信发送成功'
        })

